const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 'add',
    info: null,
    pics: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
    const token = extConfig.appid;
    that.setData({
      token: token
    })
    if (options.type == 'edit') {
      wx.setNavigationBarTitle({
        title: '编辑房型',
      })
      wx.showLoading({
        title: '加载中……',
      })
      wx.request({
        url: 'https://www.58zltc.com/api.php/Hotel/room/id/' + options.id + '?token=' + token,
        success: res => {
          this.setData({
            type: 'edit',
            info: res.data,
            pics: res.data.pics
          })
          wx.hideLoading()
        }
      })
    } else {
      wx.setNavigationBarTitle({
        title: '添加房型',
      })
    }

  },
  bindUploadImg: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: 'https://www.58zltc.com/api.php/Index/uploadImage' + '?token=' + that.data.token, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          success: function (res) {
            var data = JSON.parse(res.data);
            console.log(data);
            if (data.err_code > 0) {

            } else {
              var pics = that.data.pics;
              var file_name = data.data.domain;
              console.log(file_name);
              pics.push(file_name);
              that.setData({
                pics: pics
              })
            }
            //do something
          }
        })
      }
    })
  },
  formSubmit: function (e) {
    var that = this
    // console.log(e.detail.value);
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    var post_data = e.detail.value;
    var data = this.data;
    if (!data.pics) {
      wx.showToast({
        title: '请选择房间图片！',
      })
      return;
    }
    post_data.openid = app.globalData.openid;
    post_data.pics = data.pics;
    post_data.img_url = data.pics[0];
    if (data.type == 'edit') {
      post_data.id = data.info.id;
    }
    wx.request({
      url: 'https://www.58zltc.com/api.php/Hotel/roomAdd' + '?token=' + that.data.token,
      method: 'POST',
      data: post_data,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        if (res.data.err_code > 0) {
          wx.showToast({
            title: res.data.err_msg,
          })
        } else {
          wx.showToast({
            title: res.data.err_msg,
            icon: 'success'
          })
          setTimeout(function () {
            wx.navigateBack()
          }, 500)
        }
      }
    })
  },
  backto: function () {
    wx.navigateBack({})
  }
})